package com.lp.user.listener;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lp.model.constants.MQConstants;
import com.lp.user.mapper.UserFollowMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Slf4j
@Component
public class RelationListener {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserFollowMapper userFollowMapper;


    @SneakyThrows
    @RabbitListener(queues = MQConstants.USER_FOLLOW_QUEUE)
    public void followMsg(String msg) {
        log.info("MQ 收到关注消息: {}", msg);
        HashMap hashMap = objectMapper.readValue(msg, HashMap.class);
        Long followerId = objectMapper.convertValue(hashMap.get("followerId"),
                new TypeReference<Long>() { });
        Long followedId = objectMapper.convertValue(hashMap.get("followedId"),
                new TypeReference<Long>() { });
        //2.检验当前用户是否已关注
        if(userFollowMapper.selectFollowById(followerId, followedId) != null) {
            //已关注就需要取消关注
            userFollowMapper.delete(followerId, followedId);
            log.info("用户 {} 取关了 用户 {}", followerId, followedId);
        } else {
            //3.关注
            userFollowMapper.add(followerId, followedId);
            log.info("用户 {} 关注了 用户 {}", followerId, followedId);
        }
        //4.消息通知 TODO
    }

}
